package com.example.juc.big_talk_concurrent.chapter6.article2;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test2 {
    static Exchanger<String> exchanger = new Exchanger<>();
    static ExecutorService executorService = Executors.newFixedThreadPool(2);

    static CountDownLatch count = new CountDownLatch(2);

    final static String[] strA = new String[1];
    final static String[] strB = new String[1];

    public static void main(String[] args) throws InterruptedException {

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                String dataA = "123";
                try {
                    String exchange = exchanger.exchange(dataA);
                    System.out.println("B录入的数据" + exchange);
                    strB[0] = exchange;
                    count.countDown();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                String dataB = "234";
                try {
                    String exchange = exchanger.exchange(dataB);
                    System.out.println("A录入的数据" + exchange);
                    strA[0] = exchange;
                    count.countDown();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });

        count.await();

        System.out.println(strA[0].equals(strB[0]) ? "录入数据一致" : "录入数据不一致");

        executorService.shutdown();
    }
}
